from . import __path__
from bpy.props import PointerProperty, StringProperty, BoolProperty
from bpy.types import PropertyGroup, Menu, Panel, Operator, Screen, Object
import bpy
import os
import pickle
#project functions
def projectRegDir():
    path = __path__[0] + '\\project.dat'
    return path

def getProject():
    project = bpy.context.screen.components_project #@UndefinedVariable
    return project

def getProjectsDirs():
    pdir = projectRegDir()
    if os.path.exists(pdir):
        with open(pdir, 'rb') as f:
            data = pickle.load(f)
    else:
        data = []
    return data

class SetupGame():
    def __init__(self):
        self.old_selected=bpy.context.object
        self.old_all_selected=bpy.context.selected_objects
        
        #CREATE
        bpy.ops.object.add(type='EMPTY')
        bpy.ops.logic.sensor_add(type='ALWAYS')
        bpy.ops.logic.controller_add(type='PYTHON')
        o=bpy.context.object ;assert(o,Object)
        script=o.game.controllers[0] ;assert isinstance(script,bpy.types.PythonController)
        always=o.game.sensors[0]
        
        #SETUP
        always.link(script)
        always.use_pulse_true_level=True
        script.mode='MODULE'
        script.module='DynamicBGE.engine.mainloop.cycle'
        
        #LIBRERIES
        
        
    def destroy(self):
        bpy.ops.object.delete()
        for o in self.old_all_selected:
            o.select=True
    

class SelectProjectPath(Operator):
    bl_idname = 'project.select_path'
    bl_label = 'select project path'
    path = StringProperty(name='path', subtype='DIR_PATH')
    def execute(self, context):
        def saveProjectsDirs():
            pdir = projectRegDir()
            project = getProject()
            data = set(getProjectsDirs()) 
            data.add(project.path)
            
            with open(pdir, 'wb') as f:
                pickle.dump(list(data), f)
        getProject().path = self.path
        saveProjectsDirs()
        return {'FINISHED'}
    
class ProjectMenu(Menu):
    bl_idname = 'project.menu'
    bl_label = 'select project'
    
    def draw(self, context):
        layout = self.layout
        filepath = bpy.data.filepath
        if filepath != '':
            op = layout.operator('project.select_path', '<current directory>')
            op.path = '\\'.join(filepath.split('\\')[:-1])
        for d in getProjectsDirs():
            op = layout.operator('project.select_path', d)
            op.path = d
            
class ClearDirs(Operator):
    bl_idname = 'project.clear_dirs'
    bl_label = 'Clear project paths'
    def execute(self, context):
        def clearProjectDirs():
            pdir = projectRegDir()
            project = getProject()
            val = [project.path] if project.path != '' else []
            with open(pdir, 'wb') as f:
                pickle.dump(val, f)
        clearProjectDirs()
        return {'FINISHED', }
class RunGame(Operator):
    bl_idname = 'project.run_game'
    bl_label = 'Run game'
    def execute(self, context):
        setup=SetupGame()
        bpy.ops.view3d.game_start()
        setup.destroy()
        return {'FINISHED', }
class ProjectPanel(Panel):
    bl_idname = 'project.panel'
    bl_label = 'DynamicBGE'
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_context_type = 'OBJECT'
    def draw(self, context):
        layout = self.layout
        layout.operator('project.run_game')
        layout.operator('project.clear_dirs')
        project = getProject()
        layout.menu('project.menu', project.path if project.path != '' else 'select project')



class Project(PropertyGroup):
    bl_idname = 'project'
    bl_label = 'dynamicBGE project'
    path = StringProperty(name='path', subtype='DIR_PATH')
    show = BoolProperty(name='show', default=True)
    @classmethod
    def register(cls):
        Screen.components_project = PointerProperty(type=cls)

